package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.UUID;

@Service
//@Transactional
public class UserInfoServiceImpl implements IUserInfoService {

	@Autowired
	private UserInfoRepository userInfoRepository;
	@Autowired
	private IUserInfoRedisService userInfoRedisService;

	@Override
	public void save(UserInfo userInfo) {
		userInfoRepository.save(userInfo);
	}

	@Override
	public void update(UserInfo userInfo) {
		userInfoRepository.save(userInfo);
	}

	@Override
	public void delete(String id) {
		userInfoRepository.deleteById(id);
	}

	@Override
	public UserInfo get(String id) {
		return userInfoRepository.findById(id).orElse(null);
	}

	@Override
	public UserInfo findByPhoneByPassword(String username, String password) {
		UserInfo user = userInfoRepository.findByPhone(username);
		if(user == null || !user.getPassword().equals(password)){
			throw new LogicException("账号或密码有误");
		}
		return user;
	}

	@Override
	public void updateStrategyFavor(List<String> list) {
		// list第一位是userId,获取userId
		String userId = list.get(0);
		UserInfo userInfo = this.get(userId);
		// 删除userId
		list.remove(userId);
		// 设置收藏列表
		userInfo.setStrategiesFavor(list);
		this.update(userInfo);
	}

	@Override
	public void updateTravelFavor(List<String> list) {
		// list第一位是userId,获取userId
		String userId = list.get(0);
		UserInfo userInfo = this.get(userId);
		// 删除userId
		list.remove(userId);
		// 设置收藏列表
		userInfo.setTravelFavor(list);
		this.update(userInfo);
	}

	@Override
	public List<UserInfo> findByCity(String city) {
		return userInfoRepository.findByCity(city);
	}

	@Override
	public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
		// 判空
		AssertUtil.hasLength(phone, "手机号不能为空");
		AssertUtil.hasLength(nickname, "名字不能为空");
		AssertUtil.hasLength(password, "密码不能为空");
		AssertUtil.hasLength(rpassword, "确认密码不能为空");
		AssertUtil.hasLength(verifyCode, "验证码不能为空");
		// 检查手机号是否已注册
		if (checkPhone(phone)) {
			throw new LogicException("手机号已经被注册");
		}
		// 匹配密码是否一致
		AssertUtil.isEquals(password, rpassword, "密码");
		// 匹配验证码
		String code = userInfoRedisService.getVerifyCode(phone);
		AssertUtil.isEquals(verifyCode, code, "验证码");

		UserInfo userInfo = new UserInfo();
		userInfo.setPhone(phone);
		userInfo.setNickname(nickname);
		userInfo.setEmail("");
		userInfo.setPassword(password);
		userInfo.setLevel(0);
		userInfo.setCity("");
		userInfo.setHeadImgUrl("/images/default.jpg");
		// 核心属性必须自己控制,用户状态
		userInfo.setState(UserInfo.STATE_NORMAL);
		this.save(userInfo);
	}

	@Override
	public void sendVerifyCode(String phone) {
		String code = UUID.randomUUID().toString()
				.replaceAll("-", "")
				.substring(0, 4);
		StringBuilder sb = new StringBuilder();
		//  你的验证码为：1234.请不要把验证码泄露给其他人！10分钟内有效。 【xx】
		sb.append("【创信】你的验证码为：").append(code)
				.append("。请不要把验证码泄露给其他人！")
				.append(Consts.VERIFY_CODE_VAI_TIME)
				.append("分钟内有效！");
		System.out.println(code);
		System.out.println(sb);

		RestTemplate template = new RestTemplate();
		String url = "https://way.jd.com/chuangxin/VerCodesms?mobile={1}&content={2}&appkey={3}";
		// url: 发送短信请求的网址,接口
		// String.class: 返回值,请求接口完之后响应数据封装对象类型
		// uriVariables(后面的可变参数): 请求的参数,个数按需决定
		String status = template.getForObject(url, String.class,phone,sb.toString(),"936a9873547c270ad9da0d6c82c243a2");
		if (!status.contains("Success")) {
			throw new LogicException("发送失败!");
		}
		userInfoRedisService.setVerifyCode(phone, code);
	}

	@Override
	public boolean checkPhone(String phone) {
		UserInfo user = userInfoRepository.findByPhone(phone);
		return user != null;
	}

	@Override
	public List<UserInfo> list() {
		return userInfoRepository.findAll();
	}
}
